import axios, { type AxiosInstance, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios';
import URL from '../service'
import { message } from "antd";

// 定义接口返回的数据结构
interface ApiResponse<T> {
  code: number|string;
  msg: string;
  data: T;
}

// 创建 Axios 实例
const apiClient: AxiosInstance = axios.create({
  baseURL: URL, // 
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'multipart/form-data;',
  },
});

// 请求拦截器
apiClient.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem('token'); // 获取 token
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
    <T>(response: AxiosResponse<ApiResponse<T>>) => {
      if(response.data.code == 500){
        message.error(response.data.msg)
      }
      // 直接返回 data 字段中的 data 属性
      return response as T;
    },
    (error) => {
      if (error.response) {
        console.error('API Error:', error.response.status, error.response.data);
      } else if (error.request) {
        console.error('No response received:', error.request);
      } else {
        console.error('Error:', error.message);
      }
      return Promise.reject(error);
    }
  );

export default apiClient;